// pages/index/index.js
const app = getApp();

Page({
  data: {
    userInfo: null,
    coupleInfo: null,
    isLoggedIn: false,
    features: [
      { id: 1, name: '共享账本', icon: 'bill-o', path: '/pages/bill/index' },
      { id: 2, name: '待办事项', icon: 'todo-list-o', path: '/pages/todo/index' },
      { id: 3, name: '重要日期', icon: 'calendar-o', path: '/pages/date/index' },
      { id: 4, name: '甜蜜相册', icon: 'photo-o', path: '/pages/album/index' },
      { id: 5, name: '个人中心', icon: 'user-o', path: '/pages/user/index' }
    ]
  },

  onLoad() {
    // 初始化数据
    this.setData({
      isLoggedIn: app.globalData.isLoggedIn,
      userInfo: app.globalData.userInfo,
      coupleInfo: app.globalData.coupleInfo
    });
    
    // 设置监听
    this._unwatch = app.watchGlobalData({
      isLoggedIn: (val) => this.setData({ isLoggedIn: val }),
      userInfo: (val) => this.setData({ userInfo: val }),
      coupleInfo: (val) => this.setData({ coupleInfo: val })
    });
    
    // 检查登录状态
    if (!app.routeInterceptor()) return;
  },

  onUnload() {
    this._unwatch?.();
  },

  // 登录/注册导航
  navToLogin() {
    wx.navigateTo({
      url: '/pages/login/index',
      success: () => console.log('跳转到登录页成功'),
      fail: (err) => console.error('跳转失败:', err)
    });
  },
  
  navToRegister() {
    wx.navigateTo({
      url: '/pages/register/index',
      success: () => console.log('跳转到注册页成功'),
      fail: (err) => console.error('跳转失败:', err)
    });
  },
  
  // 功能导航
  navToPage(e) {
    const path = e.currentTarget.dataset.path;
    const app = getApp();
    
    // 未登录时跳登录页
    if (!app.globalData.isLoggedIn) {
      wx.navigateTo({
        url: '/pages/login/index'
      });
      return;
    }
    
    // 已登录但未绑定情侣时跳绑定页
    if (!app.globalData.coupleInfo) {
      wx.navigateTo({
        url: '/pages/couple/bind'
      });
      return;
    }
    
    // 正常跳转
    wx.navigateTo({
      url: path
    });
  },

  navToCoupleBind() {
    wx.navigateTo({
      url: '/pages/couple/bind'
    });
  },

  navToCoupleDetail() {
    wx.navigateTo({
      url: '/pages/couple/detail'
    });
  }
})